Imports Microsoft.Web.Services2.Messaging
Imports Microsoft.Web.Services2
Imports Microsoft.Web.Services2.Addressing
Imports System.Xml
Imports System.Net
Imports System.Text
Imports System.IO

Imports Microsoft.Web.Services2.Security
Imports Microsoft.Web.Services2.Security.Tokens
Imports Microsoft.Web.Services2.Security.X509
Imports System.Security.Cryptography

Public Class CustomSOAPClient
    Inherits SoapClient


    Public strCertificateName As String = ""

    Public Function SendRequest(ByVal objUri As String, ByVal methodName As String, ByVal objxml As String) As String
        Dim uri As New System.Uri(objUri)
        Dim objsoapreq As New SoapEnvelope
        Me.Destination = New EndpointReference(uri)

        If strCertificateName <> "" Then
            objsoapreq.Context.Security.Tokens.Add(GetSecurityToken(strCertificateName))
            objsoapreq.Context.Security.Elements.Add(New MessageSignature(GetSecurityToken(strCertificateName)))
        End If

        objsoapreq.Body.InnerXml = objxml
        Dim objResponse As SoapEnvelope
        Try
            objResponse = MyBase.SendRequestResponse(methodName, objsoapreq)
        Catch ex As Exception
            Return ex.ToString
        End Try

        Return objResponse.InnerXml

    End Function

    Public Function SendRequest(ByVal objUri As System.Uri, ByVal methodName As String, ByVal objxml As XmlDocument) As String




        Dim request As HttpWebRequest = WebRequest.CreateDefault(objUri)
        Dim objencoding As Encoding = New UTF8Encoding
        Dim strResponse As String
        Try

        
            request.Method = "POST"

            request.ContentType = "text/xml"
            request.Headers.Item("SOAPAction") = methodName ' "http://AmericanExpress.CSBS.WebSvc.RewardsEnrollmentEligibilityProcessor:GetCardMixTiersIn"
            request.SendChunked = False
            request.AllowAutoRedirect = True


            Dim store As X509CertificateStore = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore)
            Dim open As Boolean = store.OpenRead()


            Dim cert As X509Certificate
            Dim certs As X509CertificateCollection = store.FindCertificateBySubjectString("ServerCertificate")
            cert = CType(certs(0), Microsoft.Web.Services2.Security.X509.X509Certificate)


            request.ClientCertificates.Add(cert)




            Dim writer As New StreamWriter(request.GetRequestStream, objencoding)
            writer.Write(objxml.InnerXml)
            writer.Close()





            Dim objresponse As HttpWebResponse = request.GetResponse

            Dim stream As Stream = objresponse.GetResponseStream
            Dim streamreader As New StreamReader(stream)
            strResponse = streamreader.ReadToEnd


        Catch ex As WebException

            Dim objsoapresp As New SoapEnvelope
            Dim objErrorDom As New XmlDocument
            objErrorDom.Load(HttpContext.Current.Server.MapPath("") & "\bin\ErrorResponse.xml")

            Dim objxmlErrorNode As XmlNode = objErrorDom.SelectSingleNode("Error/ErrorMessage")
            Dim objXmlErrorDetails As XmlNode = objErrorDom.SelectSingleNode("Error/ExceptionInfo")

            objxmlErrorNode.InnerText = ex.Message
            objXmlErrorDetails.InnerText = ex.ToString
            objsoapresp.Body.InnerXml = objErrorDom.InnerXml


            strResponse = objsoapresp.InnerXml
        End Try



        Return strResponse


    End Function



    Sub InvokeSoapMethod(ByVal objHTTPRequest As HttpWebRequest)
       

    End Sub


    Public Function GetSecurityToken() As X509SecurityToken
        Dim securityToken As X509SecurityToken = Nothing
        Dim store As X509CertificateStore = _
          X509CertificateStore.CurrentUserStore( _
          X509CertificateStore.MyStore)
        Dim open As Boolean = store.OpenRead()

        Try

            Dim cert As X509Certificate
            Dim certs As X509CertificateCollection = store.FindCertificateBySubjectString("ServerCertificate")
            cert = CType(certs(0), Microsoft.Web.Services2.Security.X509.X509Certificate)

            If cert Is Nothing Then
                'MessageBox.Show("You chose not to select an X.509 " + _
                '  "certificate for signing your messages.")
                securityToken = Nothing
            ElseIf (Not cert.SupportsDigitalSignature Or _
              (cert.Key Is Nothing)) Then
                'MessageBox.Show( _
                '  "The certificate must support digital " + _
                '  "signatures and have a private key available.")
                securityToken = Nothing
            Else
                securityToken = New X509SecurityToken(cert)
            End If
        Finally
            If Not (store Is Nothing) Then
                store.Close()
            End If
        End Try
        Return securityToken
    End Function



    Public Function GetSecurityToken(ByVal strCertName As String) As X509SecurityToken
        Dim securityToken As X509SecurityToken = Nothing
        Dim store As X509CertificateStore = _
          X509CertificateStore.LocalMachineStore( _
          X509CertificateStore.MyStore)
        Dim open As Boolean = store.OpenRead()

        Try

            Dim cert As X509Certificate
            Dim certs As X509CertificateCollection = store.FindCertificateBySubjectString(strCertName)
            cert = CType(certs(0), Microsoft.Web.Services2.Security.X509.X509Certificate)

            If cert Is Nothing Then
                'MessageBox.Show("You chose not to select an X.509 " + _
                '  "certificate for signing your messages.")
                securityToken = Nothing
            ElseIf (Not cert.SupportsDigitalSignature Or _
              (cert.Key Is Nothing)) Then
                'MessageBox.Show( _
                '  "The certificate must support digital " + _
                '  "signatures and have a private key available.")
                securityToken = Nothing
            Else
                securityToken = New X509SecurityToken(cert)
            End If
        Finally
            If Not (store Is Nothing) Then
                store.Close()
            End If
        End Try
        Return securityToken
    End Function


End Class
